<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/1
 * Time: 13:08
 */
namespace Admin\Model;
use IDCU\Model\RelationModel;

class ZoneModel extends RelationModel
{
    protected $_validate = array(
        array('no','require','园区编码必填',1,'regex',3),
        array('community_id','require','小区ID缺失',1,'regex',3),
//        array('name','require','必填',1,'regex',3),
        array('no','/^\d{2}$/','园区编码格式不正确',0,'regex',1),
        array('community_id','require','上级小区编号不能为空'),
        array('no,community_id','checkNo1','园区编码已存在',0,'callback',1),
        array('no,id,community_id','checkNo2','园区编码已存在',0,'callback',2)
    );

    protected $_auto = array(
    );

    protected $_link = array(
        'Community' => array(
            'mapping_type' => self::BELONGS_TO,
            'class_name' => 'Community',
            'mapping_name' => 'community',
            'foreign_key' => 'community_id',
        ),
        'Building' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'Building',
            'mapping_name' => 'buildings',
            'foreign_key' => 'zone_id'
        ),
        'Unit' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'Unit',
            'mapping_name' => 'units',
            'foreign_key' => 'zone_id'
        ),
        'Room' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name' => 'Room',
            'mapping_name' => 'rooms',
            'foreign_key' => 'zone_id'
        ),
    );

    public function _before_write(&$data)
    {
        parent::_before_write($data); // TODO: Change the autogenerated stub
        if($data['community_id']){
            $community = D('Community')->find($data['community_id']);
            $data['full_parent_name'] = $community['full_parent_name'].$community['name'];
            if($data['no']){
                $data['no'] = $community['no'].$data['no'];
            }
        }
    }

    public function _after_insert($data, $options)
    {
        parent::_after_insert($data, $options); // TODO: Change the autogenerated stub
        M('Community')->where(array('id'=>$data['community_id']))->setInc('children_count',1);
    }

    function checkNo1($param){
        $zones = $this->field('no')->where(array('community_id' => $param['community_id']))->select();
        foreach($zones as $k=>$v){
            if(substr($v['no'],-2) == $param['no']){
                return false;
            }
        }
        return true;
    }

    function checkNo2($param){
        $zones = $this->field('no')->where(array('community_id' => $param['community_id'],'id'=>array('neq',$param['id'])))->select();
        foreach($zones as $k=>$v){
            if(substr($v['no'],-2) == $param['no']){
                return false;
            }
        }
        return true;
    }
}